import Fly from 'flyio/dist/npm/wx'
const fly = new Fly()
import qs from "qs";
import encrypt from "./encrypt.js";
import decrypt from "./decrypt.js";

const isProduction = !!(process.env.NODE_ENV === 'production')
fly.config.timeout = 5000;
fly.config.baseURL = isProduction ? 'https://api.douluotianxia.com' : 'https://api.douluotianxia.com';
fly.interceptors.request.use(
	config => {
		const memberId = wx.getStorageSync('memberId');
		// const token = 158977206200540150574
		if (memberId) {
			if (config.body) {
				config.body.memberId = memberId;
			} else {
				config.body = {
					memberId
				}
			}
		}
		// if (token) {
		// 	if (config.body) {
		// 		config.body.token = token;
		// 	} else {
		// 		config.body = {
		// 			token: token
		// 		}
		// 	}
		// }
		if (typeof config.body != 'object') {
			config.body = {}
		}
		console.log('入参',JSON.stringify(config.body),config.url)
		const reqData = encrypt(config.body);
		config.body = qs.stringify(reqData);
		config.responseType = 'text';
		config.headers = {'Content-Type': 'application/x-www-form-urlencoded'}
		config.headers.clientType = 3;
		return config;
	},
	error => {
		return Promise.reject(err);
	}
);
//
//响应拦截器即异常处理
fly.interceptors.response.use(response => {
	if (response != null) {
		const respData = decrypt(response.data);
		let respJson = JSON.parse(respData);
		console.log('response',respJson);
		let respCode = respJson.code;
		if (respCode == 401) {
			wx.navigateTo({
				url: '/pages/login/main?type=1'
			});
		} else if (respCode == 402) {
			if (respJson.data.memberId) return respJson;
			wx.navigateTo({
				url: '/pages/login/main?type=2'
			});
		} else if (respCode !== 0) {
			wx.showToast({title: respJson.msg,icon:'none',duration: 2000})
		}
		return respJson
	}
}, err => {
	wx.showToast({title: '您的网络不稳定，请稍后再试',duration: 2000})
	console.log('err',err.response);
	return Promise.resolve(err.response)
});


export const GET = (url, params) => {
	return fly.get(`${url}`, params)
}
export const POST = (url, params) => {
	return fly.post(`${url}`, params)
}
